/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package cn.iocoder.yudao.framework.server.websocket;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.util.id.IdUtils;
import cn.iocoder.yudao.framework.message.ClientRequest;
import cn.iocoder.yudao.module.infra.util.TraceIdUtil;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 王广帅
 * @since 2021/5/30 19:33
 */
@Slf4j
public class WebSocketDecoderHandler extends SimpleChannelInboundHandler<Object> {

    /**
     * 读取连接消息
     *
     * @param ctx 连接管理类
     * @param msg 网络消息
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        try {
            TraceIdUtil.setTraceId(IdUtils.generatorId());
            if (msg instanceof TextWebSocketFrame) {
                try {
                    final String receiveMsg = ((TextWebSocketFrame) msg).text();
                    log.debug("收到客户端WebSocket消息: {}", receiveMsg);
                    final ClientRequest clientRequest = JSON.parseObject(receiveMsg, ClientRequest.class);
                    ctx.fireChannelRead(clientRequest);
                } catch (Throwable e) {
                    log.warn("处理客户端WebSocket消息异常", e);
                    ctx.fireExceptionCaught(e);
                }
            } else {
                ctx.fireChannelRead(msg);
            }
        } finally {
            TraceIdUtil.removeTraceId();
        }
    }

}
